package game;

import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener ;
import java.awt.event.MouseEvent ;
import java.awt.event.InputEvent ;
import java.awt.image.MemoryImageSource;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.Timer;

public class Trust extends Game {
    double p1_init_money = 3.0;              /*p1 initial money*/
    double increment;
    double multiplier;
    double p1_money_passed = 0.0;            /*money passed by p1 to p2*/
    double p1_money_exp = 0.0 ;              /*money p1 expects p2 to pass*/
    double p2_money_passed = 0.0 ;           /*money p2 passes*/
    double p2_money_exp = 0.0 ;              /*Money, p1 thinks p2 expects from him*/
    double p2_money_ava = 0.0 ;              /*Money available to p2 = (p1_money_passed * 3)*/
    double money_won = 0.0;                  /*final money won by player 1*/
    String stage = "1" ;                     /*maintains the state in which the game currently is*/
    int totalTime=60,secs = totalTime, timeTaken=0;
    Timer time = new Timer(1000, new TimeListener());

	/** List of values that user can choose to send. Used in chooser JList. */
	LinkedList<String> moneyValues = new LinkedList<String>();

	/** Number of values to display in the chooser JList. */
	final int LIST_SIZE = 5;

	/** Half of list size. */
	int halfList;

	/** Maximum number of values the user could possibly choose given the
	 increment, and starting and stopping values. */
	int maxValues;

	/** List index we've displayed for the chooser list. */
	int listIndex = 0;

	/** Amount of time, in seconds, the subject spent making their decision. */
	int playerThinkTime = 0;

	// Game log constants.
	final int GL_GIVE = 1; // How much money p1 gives to p2.
	final int GL_RETURN = 2; // How much money p1 thinks p2 will returns.
	final int GL_GUESS = 3; // How much money p1 thinks p2 expects from p1.
	final int GL_RECEIVE = 4; // How much money p2 actually returns to p1.
    
    public Trust (String params, int currentRep) {
        super();
//        super("",
//              false, //resizable
//              false, //closable
//              false, //maximizable
//              false);//iconifiable
//        javax.swing.plaf.InternalFrameUI ui = this.getUI();
//        ((javax.swing.plaf.basic.BasicInternalFrameUI)ui).setNorthPane(null);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

		String paramPart[] = params.split (",");
        p1_init_money = Double.parseDouble(paramPart[2]);
        increment = Double.parseDouble(paramPart[3]);
        multiplier = Double.parseDouble(paramPart[4]);
		this.params = params;
		repTot = Integer.parseInt (paramPart[1]);
		repNum = currentRep;

        initComponents();
        l3.setText (String.format ("$%.2f", p1_init_money));
        this.setVisible(true);
        setLocation(screenSize.width/2-400, screenSize.height/2-300);
        l10.setIcon(new ImageIcon(this.getClass().getResource("/images/redAddMoney.png")));
        l11.setIcon(new ImageIcon(this.getClass().getResource("/images/greenDone.png")));

        runner.addMouseListener( new Trust.CheckMouse());
        addMouseListener( new Trust.CheckMouse());
		moneyList.addMouseListener (new Trust.CheckMouse());
		this.getGlassPane().addMouseListener(new Trust.CheckMouse());
		
        S1() ;

        time.start();
        updateTimerLabel();

        hideMouse();
    }
   
    public Trust() {
        super();
//        super("",
//              false, //resizable
//              false, //closable
//              false, //maximizable
//              false);//iconifiable
//        javax.swing.plaf.InternalFrameUI ui = this.getUI();
//        ((javax.swing.plaf.basic.BasicInternalFrameUI)ui).setNorthPane(null);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

        this.p1_init_money = 10;
        increment = 0.25;
        multiplier = 2;
        initComponents();
        l3.setText (String.format ("$%.2f", p1_init_money));
        this.setVisible(true);
        setLocation(screenSize.width/2-400, screenSize.height/2-300);
        l10.setIcon(new ImageIcon(this.getClass().getResource("/images/redAddMoney.png")));
        l11.setIcon(new ImageIcon(this.getClass().getResource("/images/greenDone.png")));

        addMouseListener( new Trust.CheckMouse());
        S1() ;

		updateTimerLabel();
        time.start();

        hideMouse();
    }

    @Override
    public synchronized void addMouseListener(MouseListener l) {
        super.addMouseListener(l);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        bg1 = new javax.swing.ButtonGroup();
        l10 = new javax.swing.JLabel();
        l11 = new javax.swing.JLabel();
        l1 = new javax.swing.JLabel();
        l2 = new javax.swing.JLabel();
        l3 = new javax.swing.JLabel();
        l4 = new javax.swing.JLabel();
        lblTime = new javax.swing.JLabel();
        l12 = new javax.swing.JLabel();
        moneyScroll = new javax.swing.JScrollPane();
        moneyList = new javax.swing.JList();

        setBackground(new java.awt.Color(255, 255, 255));
        setBorder(null);
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setMaximumSize(new java.awt.Dimension(800, 600));
        setMinimumSize(new java.awt.Dimension(800, 600));
        setPreferredSize(new java.awt.Dimension(800, 600));

        l10.setFont(new java.awt.Font("Trebuchet MS", 1, 24));
        l10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/redBtn.png"))); // NOI18N

        l11.setFont(new java.awt.Font("Trebuchet MS", 1, 24));
        l11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/greenBtn.png"))); // NOI18N

        l1.setFont(new java.awt.Font("Calibri", 1, 24));
        l1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        l1.setText("You are Player 1");

        l2.setFont(new java.awt.Font("Calibri", 1, 24)); // NOI18N
        l2.setText("You have");

        l3.setFont(new java.awt.Font("Calibri", 1, 26)); // NOI18N
        l3.setForeground(new java.awt.Color(0, 102, 255));
        l3.setText("12");

        l4.setFont(new java.awt.Font("Calibri", 1, 24));
        l4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        l4.setText("What would you like to give to Player 2 ?");

        lblTime.setFont(new java.awt.Font("Calibri", 1, 36));
        lblTime.setForeground(new java.awt.Color(153, 102, 0));
        lblTime.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/hrGlass.png"))); // NOI18N
        lblTime.setText("3:00");

        l12.setFont(new java.awt.Font("Trebuchet MS", 1, 24));

        moneyList.setFont(new java.awt.Font("Tahoma", 1, 24));
        moneyList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "$0.00", "$0.25", "$0.50", "$0.75", "$1.00" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        moneyList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        moneyList.setVisibleRowCount(5);
        moneyList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                moneyListValueChanged(evt);
            }
        });
        moneyScroll.setViewportView(moneyList);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(46, 46, 46)
                .add(l10)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 118, Short.MAX_VALUE)
                .add(l11)
                .add(36, 36, 36))
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap(341, Short.MAX_VALUE)
                .add(l2)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(l3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 86, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(276, 276, 276))
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(lblTime, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
                .addContainerGap())
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(l1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
                .addContainerGap())
            .add(layout.createSequentialGroup()
                .add(266, 266, 266)
                .add(l12)
                .addContainerGap(534, Short.MAX_VALUE))
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap(340, Short.MAX_VALUE)
                .add(moneyScroll, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 128, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(332, 332, 332))
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(l4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(lblTime, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 48, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(l1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 42, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(l2)
                    .add(l3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 29, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 35, Short.MAX_VALUE)
                .add(l4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 73, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(29, 29, 29)
                .add(moneyScroll, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 160, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(41, 41, 41)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(l10)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(l12))
                    .add(l11))
                .addContainerGap())
        );

        l4.getAccessibleContext().setAccessibleName("What would you like to give to player 2 ? ");

        pack();
    }// </editor-fold>//GEN-END:initComponents

	private void moneyListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_moneyListValueChanged
		moneyList.setSelectedIndex(halfList);
}//GEN-LAST:event_moneyListValueChanged

	/**
     * Based on the time remaining, updates the time remaining label.
     */
    private void updateTimerLabel() {
        int min = secs / 60;
        int sec = secs % 60;
        lblTime.setText (min + ":" + ((sec < 10) ? "0" : "") + sec);
    }

	/**
     * Reset the money list to its initial state. Assuming no loss of precision.
     */
	private void initMoneyList() {
		moneyValues.clear();

		// How many different values to display in the money list.
		if (stage.equals("2"))
			maxValues = (int) (p2_money_ava / increment) + 1;
		else
			maxValues = (int) (p1_init_money / increment) + 1;
		halfList = (int) Math.floor (LIST_SIZE / 2);
		int numValues = maxValues - halfList + LIST_SIZE;
		for (listIndex = maxValues-halfList;
			listIndex < numValues; listIndex++) {
			moneyValues.add (String.format ("$%.2f",
				increment * (listIndex % maxValues)));
		}
		listIndex--;
		moneyList.setListData(moneyValues.toArray(new String [LIST_SIZE]));
		moneyList.setSelectedIndex(halfList);
		moneyList.setVisible (true);
		moneyScroll.setVisible (true);
	}

	/**
     * Shift the money list to increase by one place.
     */
    private void incrementMoneyList() {
		listIndex++;
		moneyValues.remove();
		moneyValues.add (String.format ("$%.2f",
			increment * (listIndex % maxValues)));
		moneyList.setListData (
			moneyValues.toArray(new String [LIST_SIZE]));
		moneyList.setSelectedIndex (halfList);
    }

    class CheckMouse implements MouseListener{
         public void mousePressed(MouseEvent e) { hideMouse(); }
         public void mouseReleased(MouseEvent e) {}
         public void mouseEntered(MouseEvent e) {}
         public void mouseExited(MouseEvent e) {}
         public void mouseClicked(MouseEvent e) {
            int modifiers = e.getModifiers();
            if ((modifiers & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) {
                if( stage.equals("1") ) {
                    incrementMoneyList();
					String money =
						moneyList.getSelectedValue().toString().substring (1);
					p1_money_passed = Double.parseDouble (money);
                    p2_money_ava = p1_money_passed * multiplier;
                    //System.out.println( "p1_money_passed:\t" + p1_money_passed );
                    //System.out.println( "p2_money_ava:\t" + p2_money_ava );
                }
                else if( stage.equals("2")) {
                    incrementMoneyList();
					String money =
						moneyList.getSelectedValue().toString().substring (1);
					p1_money_exp = Double.parseDouble (money);
                    //System.out.println( "p1_money_exp:\t" + p1_money_exp );
                }
                else if( stage.equals("3") ){
                    incrementMoneyList();
					String money =
						moneyList.getSelectedValue().toString().substring (1);
					p2_money_exp = Double.parseDouble (money);
                    //System.out.println( "p2_money_exp:\t" + p2_money_exp );
                }
                else if( stage.equals("4")){
                    stage = "5" ;
                    l4.setText("Money sent");
                    l10.setIcon(null);
                    l11.setIcon(null);
                    l12.setIcon(null);
                    l10.repaint();
                    l11.repaint();
                    l2.setText("");
                    l3.setText("");

                    calculateResult() ;
                    money_won = p1_init_money - p1_money_passed + ( p2_money_passed * multiplier );
					double oppMoney = p1_money_passed * multiplier - p2_money_passed;
                    System.out.println( "Money Won:\t" + money_won );
                    timeTaken = totalTime - secs;
                    secs=0;

					writeLog (playerId + ",1,\"" + params + "\"," + repNum
						+ "," + repTot + ","
						+ String.format ("$%.2f", money_won) + ","
						+ String.format ("$%.2f", oppMoney));
					writeGameLog (playerId + ",1," + playerThinkTime + ","
						+ GL_RECEIVE + ","
						+ String.format ("$%.2f", p2_money_passed*multiplier));
					playerThinkTime = 0;

                    totalMoneyWon += money_won;
                    System.out.println("G.totalMoneyWon = " + totalMoneyWon) ;
                }
                else if( stage.equals("5") ){}
            }
            if ((modifiers & InputEvent.BUTTON2_MASK) == InputEvent.BUTTON2_MASK) {}
            if ((modifiers & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK) {
                if( stage.equals("1") ) {
					writeGameLog (playerId + ",1," + playerThinkTime + ","
						+ GL_GIVE + ","
						+ String.format ("$%.2f", p1_money_passed));
					playerThinkTime = 0;
                    stage = "2" ;
                    S2() ;
                }
                else if( stage.equals("2") ) {
					writeGameLog (playerId + ",1," + playerThinkTime + ","
						+ GL_RETURN + ","
						+ String.format ("$%.2f", p1_money_exp));
					playerThinkTime = 0;
                    stage = "3" ;
                    S3() ;
                }
                else if( stage.equals("3") ) {
					writeGameLog (playerId + ",1," + playerThinkTime + ","
						+ GL_GUESS + ","
						+ String.format ("$%.2f", p2_money_exp));
					playerThinkTime = 0;
                    stage = "4" ;
                    S4() ; 
                }
                else if( stage.equals("5") ) {}
            }
        }
    }

    private void hideMouse() {
        int[] pixels = new int[16 * 16];
        Image image = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(16, 16, pixels, 0, 16));
        Cursor transparentCursor = Toolkit.getDefaultToolkit().createCustomCursor(image, new Point(0, 0), "invisibleCursor");
        this.getGlassPane().setCursor(transparentCursor);
		this.getGlassPane().setVisible(true);
        runner.setCursor(transparentCursor);
    }

    public void calculateResult() {
        if( p2_money_ava == 0.0 ){
            p2_money_passed = 0.0 ;
            return ;
        }
        String line ;
        Random r = new Random();
        double probability = 0, cumm_prob =0 ;
        probability = r.nextDouble();
        System.out.println("probability: " + probability);
        try {
            BufferedReader bin = readGameData() ;
            line = bin.readLine() ; 
            line = bin.readLine() ;
            while( line != null ) {
                String str[] = line.split(",") ;
                System.out.println("Now checking : " + str[2]);
                if( p2_money_ava == Double.parseDouble(str[2]) ){
                    System.out.println("Match...Entries found for p2_money_ava: " + str[2]);
                    cumm_prob += Double.parseDouble(str[0]) ;
                    System.out.println("Cummalative : " + cumm_prob);
                    if( probability > cumm_prob ){
                        line = bin.readLine() ;
                        continue ;
                    }
                    else {
                        System.out.println("*******Match for probability found*******");
                        System.out.println("Probability: " + probability + " Cumm_prob " + cumm_prob);
                        p2_money_passed = Double.parseDouble(str[1]) ;
                        System.out.println( "p2_money_passed:\t" + p2_money_passed );
                        break ;
                    }
                }
                else if( p2_money_ava > Double.parseDouble(str[2]) ){
                    line = bin.readLine() ;
                }
                else if ( p2_money_ava < Double.parseDouble(str[2]) ) {
                    System.out.println("p2_money_ava: " + p2_money_ava + " < " + str[1] );
                    break ;
                }
            }
        }
        catch( IOException e ){
             e.printStackTrace();
             logError(e);
        }
    }

    
    class TimeListener implements ActionListener {
    	 public void actionPerformed(ActionEvent e) {
    		secs--;
			playerThinkTime++;
            if(secs>=0) {
                updateTimerLabel();
            }
            if(secs==0) {
                //time.stop();
                l11.setVisible(false);
                l10.setVisible(false);
                l12.setVisible(false);
                stage="5";
                l2.setText(null);
                l3.setText(null);
                moneyList.setVisible (false);
				moneyScroll.setVisible (false);
                l4.setText("Sorry, your time is up.");
				writeLog (playerId + ",1,\"" + params + "\"," + repNum
					+ "," + repTot + ",TimeOut,TimeOut");
				writeGameLog (playerId + ",1," + playerThinkTime
					+ ",TimeOut,TimeOut");

                totalMoneyWon += 0.0 ;
                System.out.println("G.totalMoneyWon = " + totalMoneyWon) ;
            }
            if(secs==-6) {
                time.stop();
                try {
                    setVisible(false);
                    free=true;
                } catch(Exception ex) {
                    ex.printStackTrace();
                    logError(ex);
                }
            }
    	}
    }

    /**
    * @param args the command line arguments
    */

    public void S1(){
        initMoneyList();
		secs = totalTime;
		updateTimerLabel();
        l4.setText("What would you like to give to the other player?");
    }

    public void S2(){
        initMoneyList();
		secs = totalTime;
		updateTimerLabel();
        l4.setText("How much do you expect the other player will now return to you?") ;
        l2.setText("Other player now has");
        l3.setText(String.format ("$%.2f", p2_money_ava));
    }

    public void S3(){
        initMoneyList();
		secs = totalTime;
		updateTimerLabel();
        l4.setText("How much do you think the other player expects from you?") ;
    }

    public void S4(){
        moneyList.setVisible (false);
		moneyScroll.setVisible (false);
		secs = totalTime;
		updateTimerLabel();
        l4.setText("") ;
        l12.setIcon(new ImageIcon(this.getClass().getResource("/images/redSend.png")));
        l10.setVisible(false);
        l11.setVisible(false);
        l12.repaint();
        
    }
    public static void main(String args[]) {
        /*java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
            try {
                    JFrame main = new JFrame();
                    JDesktopPane dPane = new JDesktopPane();
                    Trust frame = new Trust();
                    main.setSize(820, 620);
                    dPane.add(frame);
                    main.add(dPane);
                    main.setVisible(true);
                    dPane.setVisible(true);
                    frame.setSelected(true);
                    frame.setVisible(true);
                } catch(Exception ex) {
                    ex.printStackTrace();
                };
            }
        });*/
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup bg1;
    private javax.swing.JLabel l1;
    private javax.swing.JLabel l10;
    private javax.swing.JLabel l11;
    private javax.swing.JLabel l12;
    private javax.swing.JLabel l2;
    private javax.swing.JLabel l3;
    private javax.swing.JLabel l4;
    private javax.swing.JLabel lblTime;
    private javax.swing.JList moneyList;
    private javax.swing.JScrollPane moneyScroll;
    // End of variables declaration//GEN-END:variables

}
